<template>
    <div class="goods-add-form">
        <div class="section1">
            <div class="pro_info_title"
                style="text-align: center; display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                <div style="font-size: 18px; font-weight: bold; color: #333;">
                    {{ customer.customer_name }}&nbsp;{{ customer.customer_code }}
                </div>
                <div style=" height: 40px;width: 250px; text-align: center;line-height: 40px;float: right;">
                    <el-button plain @click="handleEdit">编辑</el-button>
                    <el-button plain @click="handleDelete">删除</el-button>
                </div>
            </div>

            <hr style="border: 0; height: 1px; background: #e0e0e0; margin: 10px 0 20px;">

            <table style="width: 100%; border-collapse: collapse; font-family: Arial, sans-serif;">
                <tbody>
                    <!-- 第一行 -->
                    <tr>
                        <td style="padding: 12px 15px; width: 15%; color: #666; font-weight: 500;">
                            所属行业</td>
                        <td style="padding: 12px 15px; width: 20%;">{{
                            industryValue(customer.customer_industry) }}</td>
                        <td style="padding: 12px 15px; width: 15%; color: #666; font-weight: 500;">
                            客户来源</td>
                        <td style="padding: 12px 15px; width: 20%;">{{
                            customer.customer_source  }}</td>
                        <td style="padding: 12px 15px; width: 15%; color: #666; font-weight: 500;">
                            联系人</td>
                        <td style="padding: 12px 15px; width: 15%;">{{
                            customer.contacts_name }}</td>
                    </tr>

                    <!-- 第二行 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            联系电话</td>
                        <td style="padding: 12px 15px;">{{ customer.contacts_phone }}
                        </td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            联系人部门</td>
                        <td style="padding: 12px 15px;">{{ customer.contacts_dept }}
                        </td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            联系人职务</td>
                        <td style="padding: 12px 15px;">{{ customer.contacts_position
                            }}</td>
                    </tr>

                    <!-- 第三行 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            销售负责人</td>
                        <td style="padding: 12px 15px;">{{
                            userValue(customer.customer_personCharge) }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            负责人部门</td>
                        <td style="padding: 12px 15px;">{{ deptValue(customer.dept_id)
                            }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            客户状态</td>
                        <td style="padding: 12px 15px;">{{
                            statusValue(customer.customer_status) }}</td>
                    </tr>


                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            客户等级</td>
                        <td style="padding: 12px 15px;"><el-rate v-model="customer.customer_level" disabled /></td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            客户邮箱</td>
                        <td style="padding: 12px 15px;">{{ customer.customer_email
                            }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            客户地址</td>
                        <td style="padding: 12px 15px;">{{
                            customer.customer_address }}</td>
                    </tr>
                    <!-- 第四行 - 客户地址 -->
                    <!-- <tr>
                        <td
                            style="padding: 12px 15px; color: #666; font-weight: 500;">
                            客户邮箱</td>
                        <td style="padding: 12px 15px;">{{ customer.customer_email }}</td>
                        <td
                            style="padding: 12px 15px; color: #666; font-weight: 500;">
                            客户地址</td>
                        <td style="padding: 12px 15px;" colspan="3">{{
                            customer.customer_address }}</td>
                    </tr> -->

                    <!-- 第五行 - 客户邮箱 -->
                    <!-- <tr>
                        
                    </tr> -->

                    <!-- 第六行 - 创建信息 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            创建人</td>
                        <td style="padding: 12px 15px;">{{ customer.create_by }}</td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">
                            创建时间</td>
                        <td style="padding: 12px 15px;" colspan="3">{{
                            customer.create_time.replace('T', ' ') }}</td>
                    </tr>

                    <!-- 第七行 - 修改信息 -->
                    <tr>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">修改人</td>
                        <td style="padding: 12px 15px;">{{ customer.update_by === 'null' ? "暂无" : customer.update_by }}
                        </td>
                        <td style="padding: 12px 15px; color: #666; font-weight: 500;">修改时间</td>
                        <td style="padding: 12px 15px;" colspan="3">{{ customer.update_time === 'null' ? '暂无' :
                            customer.update_time.replace('T', ' ') }}
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="section">
            <el-menu mode="horizontal" :default-active="activeMenu" @select="handleMenuSelect" class="inventory-menu"
                :ellipsis="false">
                <!-- <el-menu-item index="other">其他信息</el-menu-item> -->
                <el-menu-item index="sale">销售记录</el-menu-item>
                <el-menu-item index="outbound">出库记录</el-menu-item>
                <el-menu-item index="returnPage">退货记录</el-menu-item>
            </el-menu>
            <!-- 主内容区 -->

            <component :is="currentComponent" :details-data="customer.customer_code" :key="customer.customer_code"/>
        </div>

        <!-- </div> -->
        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button @click="customer_handleClose">关闭</el-button>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted, watch, toRaw, markRaw, inject } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { Delete, TurnOff } from '@element-plus/icons-vue'
import { useStore } from 'vuex';
import sale from './CustomerInfo_sale.vue'
import outbound from './CustomerInfo_outbound.vue'
import returnPage from './CustomerInfo_return.vue'
export default {
    setup() {
        const customer = reactive({
            customer_id: "",//客户id
            customer_name: "",//客户名称
            customer_code: "",//客户编号
            customer_status: "",//客户状态
            customer_source: "",//客户来源
            customer_level: "0",//客户级别
            customer_industry: "",//所属行业
            customer_email: "",//客户邮箱
            customer_address: "",//客户地址
            customer_details: "",//客户详情
            customer_personCharge: "",//销售负责人
            dept_id: "",//负责人部门
            contacts_name: "",//联系人姓名
            contacts_phone: "",//联系人电话
            contacts_dept: "",//联系人部门
            contacts_position: "",//联系人职务
            create_by: "",//创建人
            create_time: "",//创建时间
            update_by: "",//修改人
            update_time: "",//修改时间
        })

        const store = useStore()
        const router = useRouter()
        const industryOptios = ref([])
        const statusOptios = ref([])
        const userOptions = ref([])
        const deptOptions = ref([])
        const activeMenu = ref('sale')
        const content_other = ref(false)
        const content_sale = ref(false)
        const content_outbound = ref(false)
        const content_store = ref(false)
        const content_visit = ref(true)
        onMounted(() => {
            getIndustry()
            getStatus()
            getUser()
            getDept()
            getCustomer()
        })

        function getIndustry() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "customer_industry"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                industryOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function industryValue(row) {
            if (!row) return "无";
            const parentDept = industryOptios.value.find((industry) => industry.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        function getStatus() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: {
                    dict_type: "customer_status"
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                statusOptios.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function statusValue(row) {
            if (!row) return "无";
            const parentDept = statusOptios.value.find((status) => status.dict_value == row);
            return parentDept ? parentDept.dict_label : "无";
        }

        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                userOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function getDept() {
            axios.get("http://localhost:5181/api/Dept/DeptOpt", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptOptions.value = result.data
            }).catch((err) => {
                console.info(err)
            });
        }

        function deptValue(row) {
            if (!row) return "无";
            const parentDept = deptOptions.value.find((dept) => dept.dept_id == row)
            return parentDept ? parentDept.dept_name : "无"
        }

        function userValue(row) {
            if (!row) return "无";
            const parentUser = userOptions.value.find((user) => user.user_id == row)
            return parentUser ? parentUser.user_name : "无"
        }

        function getCustomer() {
            const code = store.state.customerCode
            axios.get("http://localhost:5181/api/Sinv_Customer/Sinv_CustomerByCode", {
                params: {
                    code: code
                }, headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                for (const key in customer) {
                    // 排除数字类型字段（如 user_id、dept_id）
                    if (key === 'customer_personCharge' || key === 'dept_id') {
                        customer[key] = result.data[key]; // 保留数字类型
                    } else {
                        customer[key] = String(result.data[key]); // 其他字段转字符串
                    }
                    if (customer[key] == ""){
                        customer[key] = '暂无'
                    }
                }
            }).catch((err) => {
                console.info(err)
            });
        }

        function handleDelete() {
            ElMessageBox.confirm(
                '此操作将删除'+customer.customer_name+'客户信息，是否继续？',
                '警告',
                {
                    type: 'warning',
                    icon: markRaw(Delete),
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }
            )
                .then(() => {
                    axios.put("http://localhost:5181/api/Sinv_Customer/Sinv_CustomerDel", {
                        customer_id: customer.customer_id,
                        del_flag: '1'
                    }, {
                        headers: {
                            authorization: `Bearer ${localStorage.getItem('token')}`
                        }
                    }).then((result) => {
                        if (result.data > 0) {
                            ElMessage.success('客户信息删除成功！')
                            router.push("/main/Sinv/CustomerManagement")
                        } else {
                            ElMessage({
                                type: 'danger',
                                message: '客户信息删除失败！'
                            });
                        }
                    }).catch((err) => {
                        console.info(err)
                    });
                })
                .catch(() => {
                    ElMessage.info('已取消删除')
                })
        }

        function handleEdit() {
            store.commit("customerCode", customer.customer_code)
            router.push("/main/Sinv/CustomerUpdate")
        }

        const closeTab = inject('closeTab'); // 注入关闭方法
        function customer_handleClose() {
            const targetPath = "/main/Sinv/CustomerManagement";

            if (closeTab) {
                closeTab(); // 调用父组件提供的关闭方法
            }

            // 添加目标标签页（如果不存在）
            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "供应商信息",
                    name: targetPath,
                    path: targetPath
                });
            }

            // 跳转并激活目标标签页
            const activeTab = inject('editableTabsValue');
            if (activeTab) {
                activeTab.value = targetPath;
            }

            router.push(targetPath);
        }

        const menuComponentMap = {
            sale: sale,
            outbound: outbound,
            returnPage: returnPage,
        };

        // 当前显示的组件
        const currentComponent = ref(menuComponentMap.sale);

        const handleMenuSelect = (index) => {
            activeMenu.value = index;
            currentComponent.value = menuComponentMap[index];

            // 可以在此处添加数据加载逻辑
        };

        return {
            customer, industryOptios, getIndustry, statusOptios, getStatus, industryValue, statusValue, userOptions, userValue, deptOptions, deptValue,
            handleDelete, handleEdit, customer_handleClose, handleMenuSelect, content_other, content_sale, content_outbound, content_store, content_visit,
            activeMenu, currentComponent, handleMenuSelect
        }
    }
}
</script>

<style scoped>
.section {
    padding: 20px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}

.section1 {
    padding: 20px;
    height: 390px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    /* 添加阴影效果 */
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.pro_info_title {
    text-align: center;
    width: 1205px;
    height: 40px;
}

.carousel-container {
    width: 100%;
    max-width: 230px;
    margin: 0 auto;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 6px;
    overflow: hidden;
}

.customer_info_value {
    /* margin-left: 260px; */
    transform: translateX(260px) translateY(-230px);
    /* position: relative;
    top: -230px;
    left: 260px; */
    width: 945px;
    height: 330px;
    background-color: aqua;
}

.goods-add-form {
    padding: 20px;
    background-color: #fff;
}
</style>